package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"grpc/grpc_test_interceptor/proto"
	"time"
)

type customCredential struct {
}

func (c customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid": "10255",
		"key":   "1qwqhdkjdqsas5",
	}, nil
}

func (c customCredential) RequireTransportSecurity() bool {
	return false
}

func main() {
	inter := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()
		//md := metadata.New(map[string]string{
		//	"appid": "101255",
		//	"key":   "1qwqhdkjdqsas5",
		//})
		//ctx = metadata.NewOutgoingContext(context.Background(), md)

		err := invoker(ctx, method, req, reply, cc, opts...)
		fmt.Println(time.Since(start))
		return err
	}

	opt := grpc.WithUnaryInterceptor(inter)
	credentials := grpc.WithPerRPCCredentials(customCredential{})
	dial, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure(), opt, credentials)
	if err != nil {
		panic(err)
	}
	defer dial.Close()

	client := proto.NewGreeterClient(dial)
	r, err := client.SayHello(context.Background(), &proto.HelloRequest{
		Name: "bobby",
		G:    proto.Gender_MALE,
	})

	if err != nil {
		panic(err)
	}

	if err != nil {
		panic(err)
	}
	fmt.Println(r.Message)
}
